package edu.cuit.canary.servlet;

import jakarta.servlet.*;

import java.io.IOException;
import java.util.Enumeration;

/**
 * @author <a href="mailto:1020zhaodan@163.com">Adan</a>
 * @version 1.0
 * @date 2025/8/2 14:09
 */
public class LifeCycleServlet implements Servlet {
    private ServletConfig config;
    private String encoding;

    public LifeCycleServlet(){
        System.out.println("调用构造方法创建其servlet实例");
    }
    @Override
    public void init(ServletConfig config) throws ServletException {
        this.config = config;
        System.out.println("servlet生命周期方法，创建完实例后会立即调用init初始化方法,只调用一次");
        System.out.println("servlet name:" + config.getServletName());
        //获取servlet配置的初始化参数
        encoding = config.getInitParameter("encoding") == null ? "gbk" : config.getInitParameter("encoding");
        System.out.println("encoding:" + encoding);

        //获取所有的配置初始参数名称
        Enumeration<String> parameterNames = config.getInitParameterNames();
        while(parameterNames.hasMoreElements()){
            String name = parameterNames.nextElement();
            System.out.println(name + ":" + config.getInitParameter(name));
        }

        System.out.println("===================================================");
    }

    @Override
    public ServletConfig getServletConfig() {
        System.out.println("该方法供其它servlet进行调用(获取该servlet配置信息)，不是生命周期方法");
        return config;
    }

    /**
     * servlet生命周期方法:每次请求都会调用该业务方法
     * @param request 针对本次请求的请求对象
     * @param response 针对本次请求的响应对象
     * @throws ServletException
     * @throws IOException
     */
    @Override
    public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding(encoding);
        System.out.println("servlet生命周期方法,每次请求都会调用该业务方法");
        System.out.println("request:" + request);
        System.out.println("response:" + response);
        System.out.println("===================================");
    }

    @Override
    public String getServletInfo() {
        System.out.println("该方法不是生命周期，供其它servlet调用,返回该servlet的一些描述信息");
        return config.getServletName();
    }

    @Override
    public void destroy() {
        System.out.println("servlet生命周期方法(销毁方法):servlet容器卸载servlet时调用");
    }
}
